/*
 * Licensed Materials - Property of tenxcloud.com
 * (C) Copyright 2018 TenxCloud. All Rights Reserved.
 * 2018-06-13  @author lizhen
 */

package utility

import (
	"fmt"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/tools/clientcmd/api"
	"strconv"
)

type cluster interface {
	GetID() string
	GetHost() string
	GetToken() string
}

type protocol interface {
	GetProtocol() string
}

func NewClientSet(c cluster, timeoutInSecond ...int) (client kubernetes.Interface, err error) {
	var cfg *rest.Config
	if cfg, err = NewRESTConfig(c, timeoutInSecond...); err != nil {
		return
	}
	client, err = kubernetes.NewForConfig(cfg)
	return
}

func NewRESTConfig(c cluster, timeoutInSecond ...int) (cfg *rest.Config, err error) {
	id := c.GetID()
	host := c.GetHost()
	token := c.GetToken()
	config := api.NewConfig()
	if p, ok := c.(protocol); ok {
		pp := p.GetProtocol()
		config.Clusters[id] = &api.Cluster{
			Server:                fmt.Sprintf("%s://%s", pp, host),
			InsecureSkipTLSVerify: pp == "https",
		}
	} else {
		config.Clusters[id] = &api.Cluster{
			Server:                fmt.Sprintf("https://%s", host),
			InsecureSkipTLSVerify: true,
		}
	}
	config.AuthInfos[id] = &api.AuthInfo{
		Token: token,
	}
	config.Contexts[id] = &api.Context{
		Cluster:  id,
		AuthInfo: id,
	}
	config.CurrentContext = id
	overrides := new(clientcmd.ConfigOverrides)
	if len(timeoutInSecond) == 1 {
		overrides.Timeout = strconv.Itoa(timeoutInSecond[0])
	}
	builder := clientcmd.NewNonInteractiveClientConfig(*config, id, overrides, nil)
	cfg, err = builder.ClientConfig()
	return
}
